package net.sshiffon.grittyish;

import java.awt.Dimension;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Session;
import com.wittams.gritty.RequestOrigin;
import com.wittams.gritty.ResizePanelDelegate;
import com.wittams.gritty.swing.GrittyTerminal;

/**
 *
 * @author amir
 */
public class GrittyConnector {

    private static Logger logger = Logger.getLogger(GrittyConnector.class);
    public final GrittyTerminal term;
    private String title;
    private SshiffonTty tty;
    private Session session;

    public GrittyConnector(Session session, String title, GrittyTerminal term) {
    	this.session= session;
    	this.title= title;
        this.term = term;
        term.setVisible(true);
        term.getTermPanel().setVisible(true);
        
        term.getTermPanel().setResizePanelDelegate(new ResizePanelDelegate() {
            public void resizedPanel(final Dimension pixelDimension, final RequestOrigin origin) {
                if (origin == RequestOrigin.Remote) {
                    logger.debug("resize originates from remote");
                } else {
                    logger.debug("resize originates from user");
                }
            }
        });
    }

    
	public void kick() throws Exception {
        if (!term.isSessionRunning()) {
            logger.debug("attempting to open Terminal channel");
            tty = new SshiffonTty(title, session);
            logger.debug("Setting tty");
            try {
            	term.setTty(tty);
            }  catch (Exception e)
            {
            	logger.warn("error setting tty ",e);
            }
            logger.debug("Starting up terminal");
            term.start();
        } else {
            logger.debug("session already open");
        }
    }

    public Session getSession() {
        return tty.getSession();
    }

    public void quit() {
        logger.debug("quit called");
        term.stop();
    }
}
